﻿using Futuret.Core.Extensions;
using Futuret.Core.Futuret.Interface;
using Microsoft.Extensions.DependencyInjection;

namespace Future.Shared.Core.Extensions;

/// <summary>
///     Author: Riva
///     Date: 2023/7/11 14:17
///     Description:
/// </summary>
public static class ServiceCollectionExtension
{
    /// <summary>
    ///     统一注册WebApi通用服务
    /// </summary>
    /// <param name="services"></param>
    /// <param name="serviceInfo"></param>
    /// <returns></returns>
    public static IServiceCollection AddCloud(this IServiceCollection services, IAppInfo serviceInfo)
    {
        if (serviceInfo is null)
            throw new ArgumentNullException(nameof(serviceInfo));

        var webApiRegistarType = serviceInfo.AllTypes.FirstOrDefault(m =>
            m.IsAssignableTo(typeof(IDependencyRegistrar)) && m.IsNotAbstractClass(true));
        if (webApiRegistarType is null)
            throw new NullReferenceException(nameof(IDependencyRegistrar));

        if (Activator.CreateInstance(webApiRegistarType, services) is not IDependencyRegistrar webapiRegistar)
            throw new NullReferenceException(nameof(webapiRegistar));

        webapiRegistar.AddService();

        return services;
    }
}